package vip.xiaozhao.paotui.controller.pay;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import vip.xiaozhao.paotui.controller.BaseController;
import vip.xiaozhao.paotui.intf.dto.PayOrderDO;
import vip.xiaozhao.paotui.intf.dto.ResponseDO;
import vip.xiaozhao.paotui.intf.entity.PayChannelAudit;
import vip.xiaozhao.paotui.intf.enums.PaySourceEnum;
import vip.xiaozhao.paotui.intf.service.PayChannelService;
import vip.xiaozhao.paotui.intf.utils.HttpClientUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Map;

@Controller
@RequestMapping("/pay/channel")
@Slf4j
public class PayChannelController extends BaseController {


    @Resource
    private PayChannelService payChannelService;

    @PostMapping("/ajax/toPay")
    @ResponseBody
    public ResponseDO pay(PayOrderDO payOrder, HttpServletRequest request, HttpServletResponse response) throws Exception {

        //1 参数校验 2 入库 3 调用 Channel的接口，进行对外的渠道调用
        log.info("uniPay to pay ,channelDO = : " + payOrder);

        PayChannelAudit channelAudit = new PayChannelAudit();
        channelAudit.setUserId(payOrder.getUserId());
        channelAudit.setOrderId(payOrder.getBizOrderId());
        channelAudit.setEngineId(0);
        channelAudit.setPayChannel(1);
        channelAudit.setPayMethod(1);
        channelAudit.setPayAmount(payOrder.getAmount());
        channelAudit.setStatus(1);
        channelAudit.setSource(PaySourceEnum.Out.getId());
        channelAudit.setTradeNo("123453"); //这个流水号是业务主键
        channelAudit.setOutTradeNo("");
        channelAudit.setMsg(SUCCESS);
        channelAudit.setUserIp("");
        channelAudit.setPartnerId("12342");
        log.info("source = 1,channelPayservice channelaudit = "
                + channelAudit.toString());

            int result = payChannelService.insert(channelAudit);

//
            //回调地址写死了
//            Map<String, String> params = generateGeneralParams(channelAudit.getTradeNo(), channelPayDO.getOpenId(),
//                    channelAudit.getPayAmount(), "https://www.naoffer.com/pay/weixin/notify", prefix+ "/pay/order/success/" + channelPayDO.getOrderId(), userIp,prefix);
//            if (params == null) {
//                return null;
//            }

            //请求微信后台
            String url = HttpClientUtils.executeGetHttpClient("https://api.mch.weixin.qq.com/v3/pay/transactions/h5", null);

            //插入为2的流水


          return ResponseDO.success(url);
    }

    @PostMapping("/notify")
    @ResponseBody
    public String notify( HttpServletRequest request, HttpServletResponse response) throws Exception {

        log.info("weixin notify");
        Map<String,String> params = null; //按报文获取;
        log.info("receive pay nofiy ,params =:" + params);

        String outTradeNo = params.get("trade_no");
        String tradeNo = params.get("out_trade_no");
        BigDecimal amount = new BigDecimal(params.get("total_fee"));
        String sign = params.get("sign");
        String status = params.get("trade_status");

        //验签，sign
//        if(MD5Signature.verify()){
//           return SUCCESS;
//        }

        if(StringUtils.equalsIgnoreCase(status, "TRADE_SUCCESS")){
            // 1 校验   幂等
            PayChannelAudit audit = payChannelService.loadByTradeNoAndSoure(tradeNo, PaySourceEnum.AsynIn);
            if(audit != null){
                log.info("tradno has already payed");
                return SUCCESS;
            }
            // 校验证，out 1的流量
            PayChannelAudit payAudit = payChannelService.loadByTradeNoAndSoure(tradeNo, PaySourceEnum.Out);
            if(payAudit == null){
                return SUCCESS;
            }

            //金额的校验
            if(amount.compareTo(payAudit.getPayAmount()) != 0){
                return SUCCESS;
            }




            return SUCCESS;
        }


        return  SUCCESS;
    }


}
